﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AopAlliance.Intercept;
using System.Threading;
using Flower.Logging;

namespace Flower.Directory.Host.Default.Advices
{
    public class StatsCollector : IMethodInterceptor
    {
        private class StatEntry
        {
            public string MethodName;
            public long NumberOfCalls;
            public TimeSpan TotalTime;

            public TimeSpan AvgTime { get { return TimeSpan.FromMilliseconds(TotalTime.TotalMilliseconds / NumberOfCalls); } }
        }

        private static readonly Log Log = LogManager.CreateLog(typeof(StatsCollector).Name);

        private readonly ConcurrentDictionary<string, StatEntry> _stats =
            new ConcurrentDictionary<string,StatEntry>();
        private readonly Timer _printTimer;

        public StatsCollector(TimeSpan printInterval)
        {
            _printTimer = new Timer
            (
                _ => PrintStats(),
                null,
                printInterval,
                printInterval
            );
        }

        private void PrintStats()
        {
            var stat =
                _stats
                    .Values
                    .OrderByDescending(s => s.AvgTime)
                    .ToList();

            if (stat.Count > 0)
            {
                Log.Info("Statistics collected:");

                foreach (StatEntry statEntry in stat)
                {
                    var s = statEntry;
                    Log.Info
                    (
                        () =>
                            string.Format
                            (
                                "{0}: total time {1}, avg. time {2}, number of calls {3}.",
                                s.MethodName,
                                s.TotalTime,
                                s.AvgTime,
                                s.NumberOfCalls
                            )
                    );
                }
            }
        }

        public object Invoke(IMethodInvocation invocation)
        {
            var started = DateTime.Now;
            try
            {
                return invocation.Proceed();
            }
            finally
            {
                var ended = DateTime.Now;

                _stats.AddOrUpdate
                (
                    invocation.Method.Name,
                    methodName => new StatEntry 
                    {
                        MethodName = methodName,
                        NumberOfCalls = 1,
                        TotalTime = ended - started
                    },
                    (methodName, stat) => 
                    {
                        stat.NumberOfCalls++;
                        stat.TotalTime += ended - started;
                        return stat;
                    }
                );
            }
        }
    }
}
